package com.proj.android.canyondefense.core.impl;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class AndroidRenderView extends SurfaceView implements Runnable {

	private AndroidGame _game;
	private Bitmap _frameBuffer;
	private Thread _renderThread = null;
	private SurfaceHolder _holder;
	private boolean _isRunning = false;
	
	public AndroidRenderView(AndroidGame game, Bitmap frameBuffer) {
		super(game);
		this._game = game;
		this._frameBuffer = frameBuffer;
		this._holder = getHolder();
	}

	public void resume() {
		_isRunning = true;
		_renderThread = new Thread(this);
		_renderThread.start();
	}
	
	public void run() {
		Rect destRect = new Rect();
		long startTime = System.nanoTime();
		while (_isRunning) {
			if(!_holder.getSurface().isValid())
                continue;           
            
            float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
            startTime = System.nanoTime();

            _game.getCurrentScreen().update(deltaTime);
            _game.getCurrentScreen().present(deltaTime);
            
            Canvas canvas = _holder.lockCanvas();
            canvas.getClipBounds(destRect);
            canvas.drawBitmap(_frameBuffer, null, destRect, null);                           
            _holder.unlockCanvasAndPost(canvas);
		}
	}
	
	public void pause() {
		_isRunning = false;
		while(true) {
			try {
				_renderThread.join();
				break;
			} catch (InterruptedException e) {
				
			}
		}
	}

}
